package listening_function;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JTable;

public class show_data {
  static Connection conn = null;
    static Statement stmt = null;
	static ResultSet rs = null;
	static String sql = null;
	
	public show_data(String tableName,JTable table) {
		try {
			sql = "select * from "+tableName;
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/orcl", "Amy", "123");
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			
			int row =  visit_data.row_check(tableName);
			int col = table.getColumnCount();
			
			for(int i = 0; i < row; i++){
				if(rs.next()){
					for(int j = 0; j < col; j++){
						table.setValueAt(rs.getString(j+1),i,j);
					}
				}
			}
				
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	//查询
	public static void look_data(String sql,JTable table) {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/orcl", "Amy", "123");
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			
			int col = table.getColumnCount();
			
			for(int i = 0; i < 50; i++){
				if(rs.next()){
					for(int j = 0; j < col; j++){
						table.setValueAt(rs.getString(j+1),i,j);
					}
				}else{
					break;
				}
			}
				
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}